#!/usr/bin/python
# -*- coding: utf-8 -*-  
# test_client.py
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import constant.constant_value as constant
import urllib2,json

# 在 urllib2 上注册 http 流处理句柄
def upload(local_file,access_token):
    register_openers()
    # 开始对文件 "DSC0001.jpg" 的 multiart/form-data 编码
    # "image1" 是参数的名字，一般通过 HTML 中的 <input> 标签的 name 参数设置
    
    # headers 包含必须的 Content-Type 和 Content-Length
    datagen, headers = multipart_encode({
                                         "file": open(local_file, "rb"),
                                         'client_id': constant.api_client_id, 
                                         'client_secret':constant.api_client_secret,
                                         'access_token':access_token,
                                         'fileType':'thread'
                                         })
    # 创建请求对象
    request = urllib2.Request(constant.api_url_domain+constant.api_url_file_upload, datagen, headers)
    request.add_header('Referer',"http://www.cununle.com")
    request.add_header("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; MyIE9; BTRS123646; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)")
    request.add_header("Host", "www.cununle.com")
    # 实际执行请求并取得返回
    
    return1 =  urllib2.urlopen(request,data=None,timeout=3).read()
    response_dict =  json.loads(return1.encode("utf-8","ignore"))
    print response_dict;  #['file']['aid']
    return (response_dict['file']['uri'])

if __name__ =="__main__":
    local_file = "G:/tuniu/160456slf0f076f4u7jy7v.jpg"
    print upload(local_file,"3|4500102|e5acceec1e6415c70d64d7ee64e4a536");